//
//  XYChangeDateController.m
//  iFeller
//
//  Created by rimi on 15/12/16.
//  Copyright © 2015年 Wii. All rights reserved.
//

#import "XYChangeDateController.h"
#import <JTCalendar/JTCalendar.h>
#import "XYTimePickerView.h"
#import "XYLocalPush.h"
//日历控制器出现状态
typedef NS_ENUM (NSInteger, XYCalenderStatus) {
    XYCalenderStatusOut = 0,
    XYCalenderStatusIn ,
};

@interface XYChangeDateController () <UIViewControllerTransitioningDelegate, JTCalendarDelegate, XYTimePickerViewDelegate> {
    NSDate *_todayDate;
    NSDate *_minDate;
    NSDate *_maxDate;
    
    NSDate *_dateSelected;
}
@property (nonatomic, strong) JTCalendarManager *calendarManager;
@property (nonatomic, strong) JTCalendarMenuView *calendarMenuView;
@property (nonatomic, strong) JTHorizontalCalendarView *calendarContentView;

/*自定*/
@property (nonatomic, strong) UIButton *quitButton;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) XYTimePickerView *timePicker;
@end

@implementation XYChangeDateController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.transitioningDelegate = self;
        self.modalPresentationStyle = UIModalPresentationCustom;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.992 green:0.957 blue:0.824 alpha:1.000];
    self.view.layer.cornerRadius = 30;
    [self initUserInterface];
    
    [self.view addSubview:self.quitButton];
    [self.view addSubview:self.confirmButton];
}

- (void)initUserInterface {
    _calendarManager = [JTCalendarManager new];
    _calendarManager.delegate = self;
    
    self.calendarMenuView = [[JTCalendarMenuView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    self.calendarContentView = [[JTHorizontalCalendarView alloc] initWithFrame:CGRectMake(0, 50, SCREEN_WIDTH, 200)];
    
    [self.view addSubview:self.calendarMenuView];
    [self.view addSubview:self.calendarContentView];
    
    [self createMinAndMaxDate];
 
    [_calendarManager setMenuView:_calendarMenuView];
    [_calendarManager setContentView:_calendarContentView];
    [_calendarManager setDate:[self getLocalDate:[NSDate date]]];
}
#pragma mark - 自定义方法
//获取本地时间
- (NSDate *)getLocalDate:(NSDate *)date {
    NSTimeZone *localZone = [NSTimeZone localTimeZone];
    NSInteger interval = [localZone secondsFromGMTForDate:date];
    NSDate *mydate = [date dateByAddingTimeInterval:interval];
    return mydate;
}

//弹出时间选择器
- (void)pushTheTimePicker:(NSString *)date {
    [UIView animateWithDuration:1 animations:^{
        self.calendarMenuView.alpha = 0.0f;
        self.calendarContentView.alpha = 0.0f;
        self.view.frame = CGRectMake(0, 100, SCREEN_WIDTH, SCREEN_HEIGHT / 1.5);
        
        _quitButton.frame = CGRectMake(300, 400, 30, 30);
        _confirmButton.frame = CGRectMake(50, 400, 30, 30);
    } completion:^(BOOL finished) {
        _timePicker = [[XYTimePickerView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300) date:date];
        _timePicker.delegate = self;
        [self.view addSubview:_timePicker];
        self.timePicker.alpha = 0.0f;
        [UIView animateWithDuration:1 animations:^{
            self.timePicker.alpha = 1.0f;
        } completion:^(BOOL finished) {

        }];
    }];
}

#pragma mark - 代理
//关闭时间选择器
- (void)backToCalenderPicker {
    [UIView animateWithDuration:1 animations:^{
        self.confirmButton.enabled = NO;
        self.timePicker.alpha = 0.0f;
        self.view.frame = CGRectMake(0, SCREEN_HEIGHT / 4, SCREEN_WIDTH, SCREEN_HEIGHT / 2);
        _quitButton.frame = CGRectMake(300, 270, 30, 30);
        _confirmButton.frame = CGRectMake(50, 270, 30, 30);
    } completion:^(BOOL finished) {
        [self.timePicker removeFromSuperview];
        [UIView animateWithDuration:1 animations:^{
            self.calendarMenuView.alpha = 1.0f;
            self.calendarContentView.alpha = 1.0f;
        } completion:^(BOOL finished) {
            
        }];
    }];
}

- (void)isTheConfirmButtonEnabled {
    self.confirmButton.enabled = YES;
}

- (void)isTheConfirmButtonDisEnabled {
    self.confirmButton.enabled = NO;
}

#pragma mark - 懒加载
- (UIButton *)quitButton {
    if (!_quitButton) {
        _quitButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _quitButton.frame = CGRectMake(300, 270, 30, 30);
        [_quitButton setBackgroundImage:[UIImage imageNamed:@"DateQuit"] forState:UIControlStateNormal];
        [_quitButton addTarget:self action:@selector(quitDateChange) forControlEvents:UIControlEventTouchUpInside];
    }
    return _quitButton;
}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _confirmButton.frame = CGRectMake(50, 270, 30, 30);
        [_confirmButton setBackgroundImage:[UIImage imageNamed:@"confirm"] forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(confirmDateChange) forControlEvents:UIControlEventTouchUpInside];
        _confirmButton.enabled = NO;
    }
    return _confirmButton;
}

#pragma mark - block
- (void)respondsButtonWithDoneEditNotes:(XYEditDate)doneEditDate {
    self.doneEditDate = doneEditDate;
}

- (void)respondsButtonWithDoneEditQuit:(XYEditQuit)doneEditQuit {
    self.doneEditQuit = doneEditQuit;
}

#pragma mark - 点击事件
- (void)quitDateChange {
    if (self.doneEditQuit) {
        self.doneEditQuit(YES);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)confirmDateChange {
    if (self.doneEditDate) {
        NSString *dateString = [NSString stringWithFormat:@"%@ %@ %@", _timePicker.sendTime, _timePicker.hour, _timePicker.minute];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy年 MMM dd日 EEEE HH mm"];
        NSDate *finisiDate = [formatter dateFromString:dateString];
        
        NSString *finishString = [NSString stringWithFormat:@"%@", finisiDate];
//        NSLog(@"datete --- > %@", finisiDate);
//        NSLog(@"%@", finishString);
        //若是向左滑弹出日历
        if (self.CalenderStatus == XYCalenderStatusOut) {
            /*要先删除以前的*/
//            NSLog(@"%@", self.pushTime);
            [XYLocalPush cancelLocalNotification:self.pushTime];
            [XYLocalPush registerLocalNotification:finisiDate pushName:self.pushName pushRepeat:self.pushRepeat];
        }
        self.doneEditDate(finishString);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSString *)getDateFormatterDate:(NSString *)format date:(NSDate *)date{
    //选择的时间
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    NSString *string = [formatter stringFromDate:date];
    return string;
}

//点击日期
- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
    _dateSelected = dayView.date;
    NSTimeZone *localZone = [NSTimeZone localTimeZone];
    NSInteger interval = [localZone secondsFromGMTForDate:dayView.date];
    NSDate *mydate = [dayView.date dateByAddingTimeInterval:interval];
    
    //过期不进行推送
    if ([[self getDateFormatterDate:@"yyyyMMdd" date:[NSDate date]] integerValue] <= [[self getDateFormatterDate:@"yyyyMMdd" date:dayView.date] integerValue]){
        
        [self pushTheTimePicker:[self getDateFormatterDate:@"yyyy年 MMM dd日 EEEE" date:dayView.date]];
        if ([[self getDateFormatterDate:@"yyyyMMdd" date:[NSDate date]] integerValue] < [[self getDateFormatterDate:@"yyyyMMdd" date:dayView.date] integerValue]) {
            self.confirmButton.enabled = YES;
        }
    }

    NSLog(@"%@", mydate);
    
    // Animation for the circleView
    dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
    [UIView transitionWithView:dayView
                      duration:.3
                       options:0
                    animations:^{
                        dayView.circleView.transform = CGAffineTransformIdentity;
                        [_calendarManager reload];
                    } completion:nil];
    
    
    // Load the previous or next page if touch a day from another month
    
    if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]) {
        if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending) {
            [_calendarContentView loadNextPageWithAnimation];
        } else {
            [_calendarContentView loadPreviousPageWithAnimation];
        }
    }
}

// Exemple of implementation of prepareDayView method
// Used to customize the appearance of dayView
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
    // Today
    if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = [UIColor blueColor];
        dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
    }
    // Selected date
    else if(_dateSelected && [_calendarManager.dateHelper date:_dateSelected isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = [UIColor redColor];
        dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
    }
    // Other month
    else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor lightGrayColor];
    }
    // Another day of the current month
    else{
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor blackColor];
    }
    
    if([self haveEventForDay:dayView.date]){
        dayView.dotView.hidden = NO;
    }
    else{
        dayView.dotView.hidden = YES;
    }
}

#pragma mark - CalendarManager delegate - Page mangement
// Used to limit the date for the calendar, optional
- (BOOL)calendar:(JTCalendarManager *)calendar canDisplayPageWithDate:(NSDate *)date{
    return [_calendarManager.dateHelper date:date isEqualOrAfter:_minDate andEqualOrBefore:_maxDate];
}

- (void)calendarDidLoadNextPage:(JTCalendarManager *)calendar{
    //    NSLog(@"Next page loaded");
}

- (void)calendarDidLoadPreviousPage:(JTCalendarManager *)calendar{
    //    NSLog(@"Previous page loaded");
}

#pragma mark - Fake data

- (void)createMinAndMaxDate {
    _todayDate = [NSDate date];
    
    // Min date will be 2 month before today
    _minDate = [_calendarManager.dateHelper addToDate:_todayDate months:0];
    
    // Max date will be 2 month after today
    _maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:12];
}

// Used only to have a key for _eventsByDate
- (NSDateFormatter *)dateFormatter {
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"dd-MM-yyyy";
    }
    return dateFormatter;
}

- (BOOL)haveEventForDay:(NSDate *)date {
    return NO;
}

#pragma mark - <UIViewControllerTransitioningDelegate>
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    return [WiiKit transitionWithTransitionType:WiiPresentTransitionPresent];
}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    return [WiiKit transitionWithTransitionType:WiiPresentTransitionDismiss];
}
@end
